package com.ewili.x.special.task.thread.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ewili.framework.utils.DateUtils;
import com.ewili.framework.utils.ExceptionUtils;
import com.ewili.framework.utils.HttpClientUtils;
import com.ewili.framework.utils.StringUtils;
import com.ewili.x.special.dao.inter.EastMoneyTradableHolderDao;
import com.ewili.x.special.dao.inter.StockDao;
import com.ewili.x.special.dao.inter.TradableHolderDao;
import com.ewili.x.special.entity.EastMoneyTradableHolder;
import com.ewili.x.special.entity.TradableHolder;
import com.ewili.x.special.task.thread.inter.TradableHolderThreadTask;
import com.ewili.x.special.utils.WangYiUtils;
import com.ewili.x.special.vo.SeasonVo;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wonder
 */
@Slf4j
@Component
public class TradableHolderThreadTaskImpl implements TradableHolderThreadTask {

    @Autowired
    private TradableHolderDao tradableHolderDao;

    @Autowired
    private EastMoneyTradableHolderDao eastMoneyTradableHolderDao;

    @Autowired
    private StockDao stockDao;

    @Async("myTaskAsyncPool")
    @Override
    public void spideTradableHolder(String code) {

        List<SeasonVo> seasonVos = WangYiUtils.getSeason("http://quotes.money.163.com/f10/gdfx_" + code + ".html#01d02", "十大流通股东");

        for (SeasonVo seasonVo : seasonVos) {
            String url = "http://quotes.money.163.com/service/gdfx.html?ltdate=" + DateUtils.format(seasonVo.getEndDate(), DateUtils.yyyy_MM_dd) + "%2C" + DateUtils.format(seasonVo.getStartDate(), DateUtils.yyyy_MM_dd) + "&symbol=" + code;
            try {
                this.spideTradableHolder(url, code, seasonVo.getSeason(), seasonVo.getStartDate(), seasonVo.getEndDate());
            } catch (Exception e) {
                log.error("url:{}", url, e);
            }
        }
    }


    @Override
    public void spideTradableHolder(String url, String stockCode, Date season, Date startDate, Date endDate) {
        Boolean isExists = tradableHolderDao.existsByStockCodeAndSeason(stockCode, season);
        if (isExists) {
            return;
        }
        try {
            Document content = Jsoup.connect(url).get();
            if (content.toString().contains("暂无数据")) {
                return;
            }
            Elements elements = content.getElementsByTag("tr");

            List<TradableHolder> tradableHolders = new ArrayList<>();

            for (int i = 0; i < elements.size(); i++) {
                if (i == 0) {
                    continue;
                }
                Element element = elements.get(i);
                Elements contents = element.getElementsByTag("td");
                Boolean isTradableHolderExists = tradableHolderDao.existsByStockCodeAndSeasonAndShareholderName(stockCode, season, contents.get(0).text());
                if (isTradableHolderExists) {
                    continue;
                }
                TradableHolder tradableHolder = new TradableHolder();
                tradableHolder.setShareholderName(contents.get(0).text());
                tradableHolder.setProportion(Double.valueOf(contents.get(1).text().replace("%", "")));
                tradableHolder.setCurrentHold(Double.valueOf(contents.get(2).text().replaceAll(",", "")));
                tradableHolder.setChangeStocks(contents.get(3).text());
                tradableHolder.setStockCode(stockCode);
                tradableHolder.setSeason(season);
                tradableHolder.setStartDate(startDate);
                tradableHolder.setEndDate(endDate);

                tradableHolders.add(tradableHolder);
            }

            tradableHolderDao.saveAll(tradableHolders);

        } catch (IOException e) {
            ExceptionUtils.propagate(e);
        }
    }

    //@Async("myTaskAsyncPool")
    @Override
    public void spideEastMoneyTradableHolder(String market, String code) {
        String url = "http://f10.eastmoney.com/ShareholderResearch/ShareholderResearchAjax?code=" + market + code;
        String content = HttpClientUtils.getContent(url, 30000, 30000);
        JSONObject jsonObject = JSONObject.parseObject(content);
        JSONArray jsonArray = jsonObject.getJSONArray("sdltgd");
        if (jsonArray.size() == 0) {
            return;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONArray joArray = jsonArray.getJSONObject(i).getJSONArray("sdltgd");
            for (int j = 0; j < joArray.size(); j++) {
                EastMoneyTradableHolder eastMoneyTradableHolder = new EastMoneyTradableHolder();
                JSONObject jo = joArray.getJSONObject(j);
                try {
                    Date date = DateUtils.parseDate(jo.getString("rq"), DateUtils.yyyy_MM_dd);
                    eastMoneyTradableHolder.setDate(date);
                } catch (ParseException e) {
                    ExceptionUtils.propagate(e);
                }
                Integer rank = Integer.valueOf(jo.getString("mc"));
                String holderName = jo.getString("gdmc");
                String stockProperty = jo.getString("gdxz");
                String stockType = jo.getString("gflx");
                Double cirStocks = Double.valueOf(jo.getString("zltgbcgbl").replace("%", ""));
                String changeRateStr = jo.getString("bdbl");
                if (StringUtils.contains(changeRateStr, "%")) {
                    changeRateStr = changeRateStr.replace("%", "");
                } else {
                    changeRateStr = "0.0";
                }
                Double changeRate = Double.valueOf(changeRateStr);
                String changeStocks = jo.getString("zj");

                eastMoneyTradableHolder.setChangeRate(changeRate);
                eastMoneyTradableHolder.setChangeStocks(changeStocks);
                eastMoneyTradableHolder.setCirStocks(cirStocks);
                eastMoneyTradableHolder.setHolderName(holderName);
                eastMoneyTradableHolder.setRanks(rank);
                eastMoneyTradableHolder.setStockProperty(stockProperty);
                eastMoneyTradableHolder.setStockType(stockType);
                eastMoneyTradableHolder.setStockCode(code);

                boolean isHolderExists = eastMoneyTradableHolderDao.existsByHolderNameAndStockCodeAndDate(holderName, code, eastMoneyTradableHolder.getDate());
                if (isHolderExists) {
                    continue;
                }
                eastMoneyTradableHolderDao.save(eastMoneyTradableHolder);
            }
        }


    }

    @Override
    public void spideEastMoneyTradableHolder() {

        String url = "http://data.eastmoney.com/gdfx/HoldingDetail.aspx";

    }


}
